package zhh.tangbao.system.aop;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import zhh.tangbao.syslog.dao.SystemLogDao;
import zhh.tangbao.syslog.entity.SystemLog;
import zhh.tangbao.system.annotation.Log;
import zhh.tangbao.system.constant.DataStatus;
import zhh.tangbao.system.manager.AsyncManager;
import zhh.tangbao.system.manager.factory.AsyncFactory;
import zhh.tangbao.system.utils.HttpServletRequestUtil;
import zhh.tangbao.system.utils.SystemTimeHolderUtil;
import zhh.tangbao.system.utils.UserHolderUtil;
import zhh.tangbao.user.cache.UserCache;
import zhh.tangbao.user.vo.UserVo;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 2022/11/6
 * @author 粥灰灰
 * @version 1.0
 * 根据是否表注@Log注解来进行系统日志记录
 */

@Component
@Aspect
@Order(value = 3) // 数值越小优先级越高
public class LogAop {

    @Autowired
    private UserCache userCache;

    @Autowired
    private UserHolderUtil userHolderUtil;

    @Autowired
    private SystemTimeHolderUtil systemTimeHolderUtil;

    private static final Logger log = LoggerFactory.getLogger(LogAop.class);

    /** 排除敏感属性字段，字段名必须符合，否则在序列化地时候无法忽略 */
    public static final String[] EXCLUDE_PROPERTIES = {"password", "oldPassword", "newPassword", "confirmPassword"};

    /** 配置织入点 */
    @Pointcut("@annotation(zhh.tangbao.system.annotation.Log)")
    public void controllerLog() {
    }

    @Before(value = "@annotation(controllerLog)")
    public void before(Log controllerLog) {
        systemTimeHolderUtil.setCurrentTime();
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) {
        handleLog(joinPoint, controllerLog, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e 异常
     */
    @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) {
        handleLog(joinPoint, controllerLog, e, null);
    }

    @Resource
    private SystemLogDao systemLogDao;

    protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) {
        try {
            // 获取当前的用户，登录接口需要在业务中直接放入User
            UserVo currentUser = userHolderUtil.getCurrentUser();
            // *========数据库日志=========*//
            SystemLog systemLog = new SystemLog();
            // 请求的地址
            systemLog.setIp(HttpServletRequestUtil.getIp());
            systemLog.setInterfaceUrl(HttpServletRequestUtil.getUrl());
            systemLog.setRequestMethod(HttpServletRequestUtil.getRequestMethod());
            systemLog.setFunctionName(controllerLog.function());
            systemLog.setModuleName(controllerLog.moduleName());
            systemLog.setTimeConsuming(systemTimeHolderUtil.getCurrentConsuming());
            if (currentUser != null) {
                systemLog.setUserName(currentUser.getUserName());
                systemLog.setUserAccount(currentUser.getUserAccount());
                systemLog.setBaseCreateInfo(currentUser.getId(), DataStatus.ENABLE);
            } else {
                systemLog.setUserName("游客访问");
                systemLog.setBaseCreateInfo(null, DataStatus.ENABLE);
            }
            if (e != null) {
                systemLog.setErrorMsg(e.getMessage());
            }
            // 是否记录请求内容
            if (controllerLog.isSaveRequestData()) {
                String requestValue = getRequestValue(joinPoint);
                systemLog.setJsonRequest(requestValue);
            }
            if (controllerLog.isSaveResponseData()) {
                String responseValue = getResponseValue(jsonResult);
                systemLog.setJsonResponse(responseValue);
            }
            AsyncManager.me().execute(AsyncFactory.recordOper(systemLog));
        } catch (Exception exp) {
            StackTraceElement element = exp.getStackTrace()[0];
            // 记录本地异常日志
            log.error("系统日志记录异常");
            log.error("{}.{}[{}]: {}", element.getClassName(), element.getMethodName(), element.getLineNumber(), exp.getMessage());
        }
    }

    /**
     * 获取请求的参数，放到log中
     */
    private String getRequestValue(JoinPoint joinPoint) {
        // 忽略某些字段地序列化
        PropertyPreFilters.MySimplePropertyPreFilter mySimplePropertyPreFilter = excludePropertyPreFilter();
        Map<String, String[]> params = HttpServletRequestUtil.getRequestFormParams();
        if (CollUtil.isNotEmpty(params)) {
            return JSONObject.toJSONString(params, mySimplePropertyPreFilter);
        } else {
            Object[] args = joinPoint.getArgs();
            if (ArrayUtil.isNotEmpty(args)) {
                return JSONObject.toJSONString(args, mySimplePropertyPreFilter);
            }
        }
        return null;
    }

    private String getResponseValue(Object jsonResult) {
        if (ObjectUtil.isNotEmpty(jsonResult)) {
            return JSONObject.toJSONString(jsonResult, excludePropertyPreFilter());
        }
        return null;
    }

    /**
     * 忽略敏感属性
     */
    public PropertyPreFilters.MySimplePropertyPreFilter excludePropertyPreFilter() {
        return new PropertyPreFilters().addFilter().addExcludes(EXCLUDE_PROPERTIES);
    }

}
